/*
* Modbus ASCII serial protocol for IOTester
 * @author Beke András (beke.andras.mkolc@gmail.com)
 * Thanks for Raphael Blatter (raphael@blatter.sg)
 * @author heavily using code examples from the RXTX-website (rxtx.qbang.org)
 */
package iotester;
import java.io.InputStream;

/**
 * MBASCII serial protocol interpreter is derived from VProtocolClass 
 */
public class MBASCII implements VProtocolClass {

  /**
   * Debugger class for the in/out datas inspecting. 
   */
  
 	public DebugContact contact;
  
   /**
   * Defines the maximum message length in bytes
   * (=<tt>256</tt>).
   */
  public static final int MAX_MESSAGE_LENGTH = 256;

  /**
   * Defines a virtual number for the FRAME START token (COLON).
   */
  public static final int FRAME_START_CHAR = ':';
  
  /**
   * Defines a virtual number for the FRAME_END token (CR LF).
   */
  public static final int FRAME_END = 0x0D0A;
  
  /**
   * Incoming message buffer of ASCII MODBUS message;
   */
  
  private char[] msgbuf;

  private static int modbus_addr;
      
  public MBASCII(){
    msgbuf = new char[MAX_MESSAGE_LENGTH];
    contact = new DebugContact();
  }
  
  /**
   * 
   * @param buffer
   * @param len 
   */
  public void ReadPacket(InputStream in)
    { int next_data; int dataptr;
      try {
         /* Waiting for FRAME_START_CHAR */
        
        while ((next_data = in.read()) != FRAME_START_CHAR);
        
        /** @TODO
         * Must be take out the synchronized 
         */ 
        /*        synchronized (m_InBuffer) {
          m_ByteInOut.reset();*/
        
        /**@TODO
         * read datas from serial line to msgbuffer;
         */
        
        dataptr = 0;
        
//          while ((in = m_InputStream.read()) != FRAME_END) {
          while ((next_data = in.read()) != FRAME_END) {
            if (next_data == -1) {
              throw new ModbusException("I/O exception - Serial port timeout.");
            }
            msgbuf[dataptr++] = (char)(next_data);
            if (dataptr >= MAX_MESSAGE_LENGTH) {
              throw new ModbusException("No frame end received");
            }    
        }
      contact.writeLog(3, new String(msgbuf));
      }catch (Exception ex) {
//        throw (iotester.ModbusASCIIException())
      }
          
          
  }
}
